﻿
/*添加圆角*/
(function ($) {
    $.fn.radius = function () {
        return this.each(function () {
            $(this).css({ "border": "1px solid #C3CED9", "border-radius": "5px 5px 5px 5px", "font-size": "14px", "line-height": "19px", "margin-right": "10px", " padding": "0" });
        })
    }
})(jQuery);

/*移除圆角*/
(function ($) {
    $.fn.removeRadius = function () {
        return this.each(function () {
            $(this).css({ "border": "1px solid #C3CED9", "border-radius": "0px 0px 0px 0px", "font-size": "14px", "line-height": "19px", "margin-right": "10px", " padding": "0" });
        })
    }
})(jQuery);

/*添加默认值,等同placeholder属性*/
(function ($) {
    $.fn.description = function (val) {
        var model = new text_model(val);
        var view = new text_view($(this), model);
        view.addEvent();
        return this.each(function () {
            if ($(this).val() == "") {
                view.load();
            } else {
                view.update();
            }
        })
    }
})(jQuery);

/*
    验证数字,附带tooltip效果
    @msg:提示信息
    @width:tooltip div宽度
*/
(function ($) {
    $.fn.isNumber = function (msg, width) {
        return this.each(function () {
            $(this).blur(function () {
                var bl = checkNum($(this).val());
                if (!bl) {
                    $(this).tooltip(msg, width);
                }
                else {
                    $(this).hidTooltip(this.id);
                }
            })
        })
    }
})(jQuery);

/*给textbox添加tooltip功能*/
(function ($) {
    $.fn.tooltip = function (msg, width) {
        return this.each(function () {
            tips.show(msg, this.id, 5000, "black", width);
        })
    }
})(jQuery);

/*隐藏textbox的tooltip*/
(function ($) {
    $.fn.hidTooltip = function () {
        return this.each(function () {
            tips.hidden(this.id);
        })
    }
})(jQuery);

/*datepicker 扩展*/
(function ($) {
    $.fn.datepickerExtend = function (option) {
        return this.each(function () {
            var events = [];
            $(this).datepicker({
                dateFormat: "yy-mm-dd",
            });
            var focus = function (obj) {
                $(obj).focus();
            }
        })
    }
})(jQuery);

/*
    auto complete
    @data:数据源
    @idFiled:隐藏的value
    @textFiled:显示的value
    @size:展示多少条
    @afterClick:点击后触发的callback事件
    @itemClass:每个选项的样式
    @containerClass:容器的样式
*/
(function ($) {
    $.fn.auto_Complete = function (option) {
        var m = new auto_model(option);
        var v = new auto_view($(this), m);
        m.init();
        v.init();
        return this;
    }
})(jQuery);

var auto_model = function (option) {
    this.op = {
        data: "",
        idFiled: "",
        textFiled: "",
        size: 10,
        afterClick: null,
        itemClass: "",
        containerClass: ""
    };
    //all data in model
    this.items = [];
    //all cells
    this.cells = [];

    this.extend = function (source) {
        for (var p in source) {
            if (source.hasOwnProperty(p)) {
                this.op[p] = source[p];
            }
        }
    }

    this.checkFiled = function (filed) {
        if (this.cells.length == 0) {
            this.getCells();
        }
        var bl = false;
        for (var i = 0; i < this.cells.length; i++) {
            if (filed == this.cells[i]) {
                bl = true;
            }
        }
        return bl;
    }

    this.init = function () {
        this.extend(option);
        if (this.op.data.length == 0) {
            alert("没有数据,请检查服务器!");
            return;
        }
        if (this.checkFiled(this.op.idFiled) == false || this.checkFiled(this.op.textFiled) == false) {
            alert("text/value字段没在数据属性中!");
            return;
        }
        this.loadData();
    }

    this.searchByName = function (name) {
        var temp_arr = [];
        var d = this.op.data;
        for (var i = 0; i < d.length; i++) {
            if (d[i][this.op.textFiled].indexOf(name) != -1) {
                temp_arr.push(d[i]);
            }
        }
        return temp_arr;
    }

    //get cells
    this.getCells = function () {
        if (this.cells.length == 0) {
            for (var i in this.op.data[0]) {
                this.cells.push(i);
            }
        }
    }

    //load data
    this.loadData = function () {
        if (this.cells.length == 0) {
            this.getCells();
        }
        var item = {};
        for (var i = 0; i < this.cells.length; i++) {
            item[this.cells[i]] = "";
        }
        //load data to model
        for (var i = 0; i < this.op.data.length; i++) {
            var temp = {};
            for (var j = 0; j < this.cells.length; j++) {
                temp[this.cells[j]] = this.op.data[i][this.cells[j]];
            }
            this.items.push(temp);
        }
    }
}

var auto_view = function (target, model) {
    this.model = model;
    this.target = target;

    this.styles = { width: "", height: "", top: "", left: "" };

    this.container = $("<div tag='auto_container' class='" + this.model.op.containerClass + "' style='position:absolute;display:none;overflow-y:auto;border:1px solid red;'></div>");

    //fill data
    this.fillData = function (data, itemClass) {
        if (data == undefined || data.length == 0 || data == null) {
            this.container.hide();
            return;
        }
        var d = data;

        var l = d.length >= this.model.op.size ? this.model.op.size : d.length;

        for (var i = 0; i < l; i++) {
            var _div = $("<div tag='item' style='margin-top: 5px;margin-left: 5px;margin-bottom: 5px;' class='" + itemClass + "'></div>");
            _div.attr("id", d[i][this.model.op.idFiled]);
            _div.html(d[i][this.model.op.textFiled]);

            this.container.append(_div);
        }
        $("body").append(this.container.show());
        this.setContainerStyle();

        //reg item event
        this.reg_itemEvent();
    }

    this.setContainerStyle = function () {
        this.container.css("left", core.getElementStyle.getAbsoluteLeft(this.target));
        this.container.css("top", parseInt(core.getElementStyle.getAbsoluteTop(this.target)) + parseInt(core.getElementStyle.getHeight(this.target)) + 6);
        this.container.css("width", parseInt(core.getElementStyle.getWidth(this.target)) + 2);
        this.container.css("height", "auto");
    }

    this.reg_itemEvent = function () {
        var that = this;
        this.container.find("div[tag=item]").each(function () {
            //hover
            $(this).hover(function () {
                $(this).css("background-color", "skyblue");
            }, function () {
                $(this).css("background-color", "white");
            });
            //click
            this.addEventListener("click", function (e) {
                core.event_stopPropagation(e, this)();
                that.container.hide();

                that.target.val($(this).html());
                if (that.model.op.afterClick != null && typeof that.model.op.afterClick == "function") {
                    that.model.op.afterClick(this);
                }
                else {
                    alert("afterClick未定义!");
                    return;
                }
            }, false);
        })
    }

    this.properChange = function (target, itemClass) {
        var that = this;
        $(target).bind('input propertychange', function () {
            that.container.find("div[tag=item]").each(function () {
                $(this).remove();
            })
            var d = that.model.searchByName($(this).val());
            that.fillData(d, itemClass);
        });
    }

    this.reg_targetEvent = function () {
        var that = this;
        window.document.onclick = function (e) {
            $("body div[tag=auto_container]").hide();
            core.event_stopPropagation(e, this)();
        }

        this.target.get(0).addEventListener("click", function (e) {
            core.event_stopPropagation(e)();
            that.container.show();
        }, false);

        this.properChange(this.target, this.model.op.itemClass);
    }

    this.init = function () {
        this.fillData(this.model.op.data, this.model.op.itemClass);
        this.container.hide();
        this.reg_targetEvent();
    }
}

var checkNum = function (str) {
    var reg = /^-?[1-9]+(\.\d+)?$|^-?0(\.\d+)?$|^-?[1-9]+[0-9]*(\.\d+)?$/;
    var bl = reg.test(str);
    return bl;
}

var text_model = function (description) {
    this.model = { color: "black", value: "" };
    this.description = description;
}

text_model.prototype.load = function (value) {
    if (value == "" || value == this.description) {
        this.model = { color: "silver", value: this.description };
    }
    else {
        this.model = { color: "black", value: value };
    }
}

text_model.prototype.focus = function (value) {
    if (value == "" || value == this.description) {
        this.model = { color: "black", value: "" };
    }
    else {
        this.model = { color: "black", value: value };
    }
}

text_model.prototype.blur = function (value) {
    if (value == "" || value == this.description) {
        this.model = { color: "silver", value: this.description };
    }
    else {
        this.model = { color: "black", value: value };
    }
}

var text_view = function (el, model) {
    this._el = $(el);
    this._model = model;
}

text_view.prototype.load = function () {
    this._model.load(this._el.val());
    this.update();
}

text_view.prototype.update = function () {
    this._el.css("color", this._model.model.color);
    this._el.val(this._model.model.value);
}

text_view.prototype.addEvent = function () {
    var that = this;
    if ($(this._el).get(0).attachEvent) {
        $(this._el).get(0).attachEvent("onfocus", function () {
            that._model.focus(that._el.val());
            that.update();
        });

        $(this._el).get(0).attachEvent("onblur", function () {
            that._model.blur(that._el.val());
            that.update();
        });
    }
    else {
        $(this._el).get(0).addEventListener("focus", function () {
            that._model.focus(that._el.val());
            that.update();
        }, false);

        $(this._el).get(0).addEventListener("blur", function () {
            that._model.blur(that._el.val());
            that.update();
        }, false);
    }
}

/*tooltip  使用规则  tips.show("输入不合法","txt_xxx",5000,"black",200)*/
var tips = {
    temp: {},
    show: function (msg, id, time, color, width) {
        var target = this._get(id);
        if (!target) { id = 'window'; }

        if (this._get(id + '_tips')) { this.remove(id); }

        msg = msg || '请输入需要提示的信息';
        color = color || 'black';
        width = width || 100;
        time = time ? parseInt(time) : false;

        if (id == 'window') {
            var y = document.body.clientHeight / 2 + document.body.scrollTop;
            var x = (document.body.clientWidth - width) / 2;
            var textAlign = 'center', fontSize = '15', fontWeight = 'bold';
        } else {
            for (var y = 0, x = 0; target != null; y += target.offsetTop, x += target.offsetLeft, target = target.offsetParent);
            var textAlign = 'left', fontSize = '12', fontWeight = 'normal';
        }

        var tipsDiv = this._create({ display: 'block', position: 'absolute', zIndex: '1001', width: (width - 2) + 'px', left: (x + 1) + 'px', padding: '5px', color: '#ffffff', fontSize: fontSize + 'px', backgroundColor: color, textAlign: textAlign, fontWeight: fontWeight, filter: 'Alpha(Opacity=50)', opacity: '0.7' }, { id: id + '_text', innerHTML: msg, onclick: function () { tips.hidden(id); } });
        document.body.appendChild(tipsDiv);
        tipsDiv.style.top = (y - tipsDiv.offsetHeight - 12) + 'px';
        document.body.appendChild(this._create({ display: 'block', position: 'absolute', zIndex: '1000', width: (width + 10) + 'px', height: (tipsDiv.offsetHeight - 2) + 'px', left: x + 'px', top: (y - tipsDiv.offsetHeight - 11) + 'px', backgroundColor: color, filter: 'Alpha(Opacity=50)', opacity: '0.7' }, { id: id + '_bg' }));
        if (id != 'window') {
            var arrow = this._create({ display: 'block', position: 'absolute', overflow: 'hidden', zIndex: '999', width: '20px', height: '10px', left: (x + 20) + 'px', top: (y - 13) + 'px' }, { id: id + '_arrow' });
            arrow.appendChild(this._create({ display: 'block', overflow: 'hidden', width: '0px', height: '10px', borderTop: '10px solid ' + color, borderRight: '10px solid #fff', borderLeft: '10px solid #fff', filter: 'Alpha(Opacity=70)', opacity: '0.8' }));
            document.body.appendChild(arrow);
        }
        this.temp[id] = id;

        if (time) { setTimeout(function () { tips.hidden(id); }, time) }

        return id;
    },
    hidden: function (id) {
        if (!id) { for (var i in this.temp) { this.hidden(i); } return; }
        var t = this._get(id + '_text'), d = this._get(id + '_bg'), a = this._get(id + '_arrow');
        if (t) { t.parentNode.removeChild(t); }
        if (d) { d.parentNode.removeChild(d); }
        if (a) { a.parentNode.removeChild(a); }
    },
    _create: function (set, attr) {
        var obj = document.createElement('div');
        for (var i in set) { obj.style[i] = set[i]; }
        for (var i in attr) { obj[i] = attr[i]; }
        return obj;
    },
    _get: function (id) {
        return document.getElementById(id);
    }
};
